package com.wyw.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

@Controller
@RequestMapping
public class HelloController {
    @RequestMapping("hello")
    @ResponseBody
    public String hello() {
        return "hello";
    }

    @RequestMapping("testThymeleaf")
    public String testThymeleaf(Model model) {
        model.addAttribute("name", "wyw");
        return "test.html";
    }

    @RequestMapping("add")
    public String add() {
        return "/user/add";
    }

    @RequestMapping("update")
    public String update() {
        return "/user/update";
    }

    @RequestMapping("toLogin")
    public String toLogin() {
        return "login";
    }

    //登录请求逻辑处理
    @RequestMapping("login")
    public String login(String userName, String password, Model model) {
        /*
         * 使用Shiro认证
         * */
        //1.获取subject对象
        Subject subject = SecurityUtils.getSubject();

        //2.封装用户数据
        System.out.println("userName:" + userName);
        System.out.println("password:" + password);
        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
        //3.执行登录方法
        try {
            subject.login(token);//如果它的底层不抛异常，就说明认证成功，它会调用UserRealm里面的doGetAuthenticationInfo方法执行认证细节
            return "redirect:/testThymeleaf";//登录成功跳转页面 重定向的是请求
        } catch (UnknownAccountException e) {//doGetAuthenticationInfo中用户名不正确会抛出UnKnownAccountException异常
            model.addAttribute("msg", "用户名不存在");
            return "login"; //返回的是视图
        } catch (IncorrectCredentialsException e) {//doGetAuthenticationInfo中密码不正确会抛出IncorrectCredentialsException异常
            model.addAttribute("msg", "密码错误");
            return "login";
        }
    }

    @RequestMapping("unAuth")
    public String unAuth(){
        return "unAuth";
    }
}
